<template>
  <div class="ruleCube-node" :class="nodeClass">
    <div class="node-main">
      <div class="node-icon">
        <svg-icon v-if="type" :icon-class="icon" :className='`icon ${type}`'/>
      </div>
    </div>
    <div class="nodebtn-main">
      <div v-if="removeEnabled" class="node-btn btn-remove el-icon-close" @click="deleteHandler"></div>
      <div v-if="editEnabled" class="node-btn btn-edit el-icon-edit" :style="{right: removeEnabled ? '28px' : '0'}" @click="editHandler"></div>
    </div>
  </div>
</template>

<script>
import { NodeConfig } from '@/model/node.model'
import store from '@/store'

export default {
  name: 'CubeNode',
  inject: ['getGraph', 'getNode'],
  data() {
    return {
      NodeConfig,
      nodeClass: {},
      type: '',
      icon: '',
      removeEnabled: true,
      editEnabled: true
    }
  },
  props: {
    noPorts: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    // 获取画布中传递的节点参数
    const node = this.getNode()
    const nodeData = node.getData()

    if (nodeData.nodeClass) {
      this.nodeClass[nodeData.nodeClass] = true
    }

    if (this.noPorts) {
      this.nodeClass['no-ports'] = true
    }

    this.type = nodeData.type || ''
    this.icon = nodeData.additionalInfo.icon || ''
    this.removeEnabled = nodeData.additionalInfo.removeEnabled
    this.editEnabled = nodeData.additionalInfo.editEnabled

    node.on('change:data', ({ current }) => {
      this.editEnabled = current.additionalInfo.editEnabled
      this.removeEnabled = current.additionalInfo.removeEnabled
    })
    document.onkeydown = (e) => {
      if (window.event.keyCode === 46) { // delete键
        const graph = this.getGraph()
        const cell = graph.getSelectedCells()[0]
        if (cell?.isNode()) { // 删除节点
          const data = cell.getData()
          if (data?.additionalInfo?.removeEnabled) {
            this.deleteNode(cell)
          }
        } else if (cell?.isEdge()) { // 删除连线
          graph.removeEdge(cell)
        }
      }
    }
  },
  methods: {
    deleteHandler() {
      const node = this.getNode()
      this.deleteNode(node)
    },
    deleteNode(node) {
      const graph = this.getGraph()
      // 并行节点需要连同父节点一起删除
      if (['AdvancedLibParallelStartNode', 'AdvancedLibParallelEndNode'].includes(node.data?.additionalInfo?.component)) {
        graph.removeNode(node.getParent())
      }
      graph.removeConnectedEdges(node)
      graph.removeNode(node)
    },
    editHandler() {
      const node = this.getNode()
      store.commit('graph/selectedItem', {
        type: 'node',
        data: node
      })
    }
  }
}
</script>
